package com.sam.android.callersl;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.lang.reflect.Method;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.RemoteException;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.internal.telephony.ITelephony;

public class IncomingCallActivity extends Activity {
     
	 
	 private static IncomingCallActivity mInst;
	private  ImageView CallerImage;
	@SuppressWarnings("unused")
	private boolean success = false;
	
	/**
     * TelephonyManager instance used by this activity
     */
    private TelephonyManager tm;
    
    /**
     * AIDL access to the telephony service process
     */
    private ITelephony telephonyService;
     
   
    	
	
	   		// used to launch activity form Receiver 
	        public static void launch(Context context,Intent intent) {

	        	try {
					Thread.sleep(500);
					 Intent i = new Intent(context, IncomingCallActivity.class);
		             i.putExtras(intent);
		             i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		             
		             context.startActivity(i);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        }



	    /// returns instance of this class object    
	    public static IncomingCallActivity instance() {
	              return mInst;
	    }
	/** Called when the activity is first created. */
	    
   @Override
   public void onCreate(Bundle savedInstanceState) {
	   
	   Log.d("CallerSL","IncomingCallActivity: onCreate: ");
	// grab an instance of telephony manager
       tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
       
       // connect to the underlying Android telephony system
       connectToTelephonyService();
       // TODO Auto-generated method stub
       super.onCreate(savedInstanceState);
       setContentView(R.layout.incomingcall);
       
       /* Get caller image and display it */
       CallerImage = (ImageView)findViewById(R.id.imgViewCaller);
       showCallerImage("http://a1.sphotos.ak.fbcdn.net/hphotos-ak-snc3/14739_214475917812_507597812_4114875_7562416_n.jpg");
      
       
       /* End caller image */
       /* Caller Number/Name Start  */
       String number = getIntent().getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
       TextView callerinfo = (TextView)findViewById(R.id.tvCallerinfo);
       callerinfo.setText(number);
       /*Caller number/name End*/
       /* Answer Button */
       Button answerButton = (Button) findViewById(R.id.btnAnswer);
       answerButton.setOnClickListener(new OnClickListener() {
           public void onClick(final View v) {
        	  
        	   
        	   try
        	   {
        		   answer();
        		   
        	   }
        	   
        	   catch(Exception ex){
        		ex.printStackTrace();
                Log.d("IncomingCallActivity CallerSL","FATAL ERROR: call to service method answerCall failed.");
        	   
               
        	   }
           }
       });
       Button endButton = (Button) findViewById(R.id.btnEndCall);
       endButton.setOnClickListener(new OnClickListener() {
           public void onClick(final View v) {
        	  
        	   /// Restarting the telephony service this will end the call -- not working
        	   // finish();
        	  try{
        	         		  
        		  reject();
        		  
        	  }
        	  catch(Exception ex)
        	  {
        		  		  // we are going to close our activity so that user can go back to normal phone app
        		  		  moveTaskToBack(true);
        		  		  finish();
                          ex.printStackTrace();
                          Log.d("IncomingCallActivity CallerSL","FATAL ERROR: call to service method endCall failed.");
                   
        	  }
        	 
        	   
        	   
           }
       });

      

       
       
       mInst = this;
      

   }
  
   public void onCallAnswered() {
   	
	   Log.d("CallerSL","IncomingCallActivity:onCallAnswered");
	   
	   	moveTaskToBack(true);
		finish();
	   
	    	
	    }
   /** From Tedd's source 
    * http://code.google.com/p/teddsdroidtools/source/browse/
    * get an instance of ITelephony to talk handle calls with 
    */
   private void connectToTelephonyService() {
           try 
           {
                   // "cheat" with Java reflection to gain access to TelephonyManager's ITelephony getter
                   @SuppressWarnings("rawtypes")
                   Class c = Class.forName(tm.getClass().getName());
                   Method m = c.getDeclaredMethod("getITelephony");
                   m.setAccessible(true);
                   telephonyService = (ITelephony)m.invoke(tm);

           } catch (Exception e) {
                   e.printStackTrace();
                   Log.e("CallerSL","FATAL ERROR: could not connect to telephony subsystem");
                   Log.e("CallerSL","Exception object: "+e);
                   finish();
           }               
   }
   
   
   /**
    * AIDL/ITelephony technique for answering the phone
    */
   private void answerCallAidl() {
           try {
                   telephonyService.silenceRinger();
                   telephonyService.answerRingingCall();
           } catch (RemoteException e) {
                   e.printStackTrace();
                   Log.e("CallerSL","FATAL ERROR: call to service method answerRiningCall failed.");
                   Log.e("CallerSL","Exception object: "+e);
           }               
   }
   
   /** 
    * AIDL/ITelephony technique for ignoring calls
    */
   private void ignoreCallAidl() {
           try 
           {
                   telephonyService.silenceRinger();
                   telephonyService.endCall();
           } 
           catch (RemoteException e) 
           {
                   e.printStackTrace();
                   Log.e("CallerSL","FATAL ERROR: call to service method endCall failed.");
                   Log.e("CallerSL","Exception object: "+e);
           }
   }
   void answerCallHandsFree()
   {
	   Context context = getBaseContext();
	   // Simulate a press of the headset button to pick up the call
       Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON);             
       buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
       context.sendOrderedBroadcast(buttonDown, "android.permission.CALL_PRIVILEGED");

       // froyo and beyond trigger on buttonUp instead of buttonDown
       Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);               
       buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
       context.sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED");
	   
	   
   }
   void answer() {
		success = true;
		
	//special thanks the auto answer open source app
	//which demonstrated this answering functionality
		//Intent answer = new Intent(Intent.ACTION_MEDIA_BUTTON);
 		//answer.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
 		//sendOrderedBroadcast(answer, null);
		
		//due to inconsistency, replaced with more reliable cheat method Tedd discovered
		try{
		answerCallAidl();
		}
		catch(Exception ex)
		{
			
			answerCallHandsFree();	
		
		}
 		//moveTaskToBack(true);
 		//finish();
	}
	
	void reject() {
		success = true;
		
		ignoreCallAidl();
       
     //  moveTaskToBack(true);
 	//	finish();
	}
   
/*User image*/
   Bitmap bmImg;
   void showCallerImage(String fileUrl){
   URL myFileUrl =null;
   try {
   myFileUrl= new URL(fileUrl);
   } catch (MalformedURLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Log.d("CallerSL:",e.getMessage());
   }
   try {
   HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
   conn.setDoInput(true);
   conn.connect();
   int length = conn.getContentLength();
   @SuppressWarnings("unused")
int[] bitmapData =new int[length];
   @SuppressWarnings("unused")
byte[] bitmapData2 =new byte[length];
   InputStream is = conn.getInputStream();

   bmImg = BitmapFactory.decodeStream(is);
   int width=150;
   int height=150;
   Bitmap resizedbitmap=Bitmap.createScaledBitmap(bmImg, width, height, true);
   CallerImage.setImageBitmap(resizedbitmap);
   } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   Log.d("CallerSL:",e.getMessage());
   }
   }

   

  


}